package com.ruoyi.oa.controller;

import cn.hutool.json.JSONObject;
import com.ruoyi.common.core.domain.R;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RequiredArgsConstructor
@RestController
@RequestMapping("/oa/weather")
public class WeatherController {
    @Resource
    private RestTemplate restTemplate;

    /**
     * 接入在线天气数据（服务提供商：高德天气 API）
     */
    @ApiOperation("接入在线天气数据")
    @GetMapping("/getweather/{arcode}")
    public R<Map<String, String>> getWeather(@ApiParam("主键")
                                             @NotNull(message = "主键不能为空") @PathVariable("arcode") String arcode) {

        //访问高德天气API
        String host = "https://restapi.amap.com/v3/weather/weatherInfo";
        String appKey = "91ff4171e7e9c806e0eb37f52a0df1ce";
        String extensions = "base";
        String output = "JSON";
        //构造请求体
        Map<String, String> hashMap = new HashMap();
        hashMap.put("city", arcode);
        hashMap.put("key", appKey);
        hashMap.put("extensions", extensions);
        hashMap.put("output", output);
        //发送请求
        JSONObject obj = restTemplate.getForObject(host + "?city={city}&key={key}", JSONObject.class, hashMap);
        //处理请求数据
        if (obj.containsKey("status") && obj.get("status").equals("1")) {
            Map<String, String> result = (Map<String, String>) obj.getJSONArray("lives").get(0);
            return R.ok(result);
        }
        return R.fail();
    }


    /**
     * 接入在线日出数据（服务提供商：和风 API）
     */
    @ApiOperation("接入在线日出数据")
    @GetMapping("/getsunrise/{arcode}")
    public R<Map<String, String>> getSunrise(@ApiParam("主键")
                                             @NotNull(message = "主键不能为空")
                                             @PathVariable("arcode") String arcode) {


        //访问和风天气API
        String host = "https://geoapi.qweather.com/v2/city/lookup";
        String appKey = "b4dba1bf0d7f4c4ca70f106a1355ab0a";
        //构造请求体
        Map<String, String> hashMap = new HashMap();
        hashMap.put("location", arcode);
        hashMap.put("key", appKey);
        //发送请求（获得城市id）

        JSONObject obj = restTemplate.getForObject(host + "?location={location}&key={key}", JSONObject.class, hashMap);
        //处理请求数据
        if (!obj.containsKey("code") || !obj.get("code").equals("200")) {
            return R.fail();
        }

        Map<String, String> result = (Map<String, String>) obj.getJSONArray("location").get(0);
        if (!result.containsKey("id") || result.get("id").isEmpty()) {
            return R.fail();
        }
        //获取城市id
        String location = result.get("id");
        host = "https://devapi.qweather.com/v7/astronomy/sun";
        //取得当天的日期
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        String dateStr = formatter.format(date);
        //构造请求体
        Map<String, String> hashMap2 = new HashMap();
        hashMap2.put("location", location);
        hashMap2.put("key", appKey);
        hashMap2.put("date", dateStr);
        //发送请求（获得城市id）
        JSONObject obj2 = restTemplate.getForObject(host + "?location={location}&key={key}&date={date}", JSONObject.class, hashMap2);
        if (!obj.containsKey("code") || !obj.get("code").equals("200")) {
            return R.fail();
        }
        //获得返回结果中的日出数据并截取出来
        String orgSunrise = obj2.get("sunrise").toString();
        String sunrise = orgSunrise.substring(orgSunrise.indexOf("T") + 1, orgSunrise.indexOf("+"));
        //获得返回结果中的日落数据并截取出来
        String orgSunset = obj2.get("sunset").toString();
        String sunset = orgSunset.substring(orgSunset.indexOf("T") + 1, orgSunset.indexOf("+"));
        //构造最后的返回结果
        Map<String, String> finalResult = new HashMap<>();
        finalResult.put("sunset", sunset);
        finalResult.put("sunrise", sunrise);
        return R.ok(finalResult);
    }
}
